package com.mjp.learn.multi.task;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 生产消费者模型
 * 利用 reentrantLock condition 来实现
 *
 * @param <T>
 */
public class Test05<T> {
    final private LinkedList<T> list = new LinkedList<>();

    final private Integer MAX = 10;

    private int count = 0;

    private Lock lock = new ReentrantLock();

    private Condition produceCondition = lock.newCondition();

    private Condition consumeCondition = lock.newCondition();

    //生产者方法
    public void put(T t) {
        try {
            lock.lock();
            while (list.size() == MAX) {
                produceCondition.await();
            }
            list.add(t);
            count++;
            consumeCondition.signalAll();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    //消费者方法
    public T get() {
        T t = null;
        try {
            lock.lock();
            while (list.size() == 0) {
                consumeCondition.await();
            }
            t = list.removeFirst();
            count--;
            produceCondition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return t;
    }

    /**
     * 获取容器一共有多少元素
     *
     * @return
     */
    public Integer getCount() {
        return this.count;
    }

    public static void main(String[] args) {
        Test05<String> container = new Test05<>();

        //启动生产者线程
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                for (int j = 0; j < 25; j++) container.put(Thread.currentThread().getName() + " " + j);
            }, "p" + i).start();

        }

        //启动消费者线程
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                for (int j = 0; j < 5; j++) System.out.println(container.get());
            }, "c" + i).start();
        }

    }
}
